﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Mvc;

using tcm.entity;
using tcm.Filters;
using tcm.request;
using tcm.utils;

namespace tcm.Controller.SystemManage
{
    [ApiController]
    [Route("tcm/param")]
    public class SysParamController : GCCAPIControllerBase
    {
        private readonly AbsGCCContext _context;
        public SysParamController(AbsGCCContext context) : base(context)
        {
            _context = context;
        }


        /// <summary>
        /// 查询字典类型列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getList")]
        [TCMAuth(permission: "system:param:list")]
        public DataResponse<List<SysDictType>> GetList([FromQuery] SysParamRequest request)
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysDictType>()
                     .WhereIf(!string.IsNullOrWhiteSpace(request.dict_name), item => item.dict_name.Contains(request.dict_name!))
                     .WhereIf(!string.IsNullOrWhiteSpace(request.dict_type), item => item.dict_type.Contains(request.dict_type!))
                     .WhereIf(request.status.HasValue, item => item.status==request.status.Value!)    
                     .Count(out var count)
                     .Page(request.PageIndex ?? 1, request.PageSize)
                     .OrderByDescending(x => x.create_date)
                     .ToList();

            return HandleData(dbres, count);
        }

        /// <summary>
        /// 查询字典类型详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("query/{id}")]
        public DataResponse<SysDictType> GetParamType([FromRoute] long id)
        {
            var res = GCCEntrance.DBManager!.LocalDB!.Queryable<SysDictType>().Where(x => x.id==id).First();

            return HandleData(res);
        }


        /// <summary>
        /// 添加字典
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        [TCMAuth(permission: "system:param:add")]
        public DataResponse<bool> AddParamType([FromBody] ParamTypeDto request)
        {
            var saveRes = false;
            try
            {
            
                if(GCCEntrance.DBManager.LocalDB.Select<SysDictType>().Where(a => a.dict_type == request.dict_type.Trim()).Any())
                    throw new Exception("字典类型已存在");
                if (GCCEntrance.DBManager.LocalDB.Select<SysDictType>().Where(a => a.dict_name == request.dict_name.Trim()).Any())
                    throw new Exception("字典名称已存在");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    request.Create(_context, HttpContext.GetToken()).Wait();
                    SysDictType sysDictType = BeanUtils.copy<SysDictType, ParamTypeDto>(request);
                    sysDictType.dict_type=sysDictType.dict_type.Trim();
                    if (GCCEntrance.DBManager!.LocalDB!.Insert(sysDictType).ExecuteAffrows() != 1)
                    {
                        throw new Exception();
                    }

                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }

            return HandleData(saveRes);
        }

        /// <summary>
        /// 更新字典
        /// </summary>
        /// <returns></returns>
        [HttpPost("update")]
        [TCMAuth(permission: "system:param:update")]
        public DataResponse<bool> UpdateParamType([FromBody] ParamTypeDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");
            try
            {

                if (GCCEntrance.DBManager.LocalDB.Select<SysDictType>().Where(a => a.dict_type == request.dict_type.Trim()&&a.id!=request.id).Any())
                    throw new Exception("字典类型已存在");
                if (GCCEntrance.DBManager.LocalDB.Select<SysDictType>().Where(a => a.dict_name == request.dict_name.Trim()&&a.id!=request.id).Any())
                    throw new Exception("字典名称已存在");
                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    var sysDictType = GCCEntrance.DBManager.LocalDB.Select<SysDictType>().Where(a => a.id == request.id).First();
                    if (sysDictType!=null)
                    {
                        request.create_by = sysDictType.create_by;
                        request.create_date = sysDictType.create_date;
                        request.Modify(_context, HttpContext.GetToken()).Wait();

                        BeanUtils.copy<SysDictType, ParamTypeDto>(request, ref sysDictType);
                        sysDictType.dict_type=sysDictType.dict_type.Trim();
                        if (GCCEntrance.DBManager.LocalDB.Update<SysDictType>(request.id).SetSource(sysDictType).ExecuteAffrows()<=0)
                        {
                            throw new Exception();
                        }
                    }
                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }
            return HandleData(saveRes);
        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <returns></returns>
        [HttpDelete("delete/{ids}")]
        //[TCMAuth(permission: "system:param:remove")]
        public DataResponse<bool> DeleteParamType ([FromRoute] string ids)
        {
            var saveRes = false;
            if (string.IsNullOrWhiteSpace(ids))
                return SystemError<bool>("id为空");

            var idList = SysHelper.SpitIntArrary(ids);

            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysDictType,SysDictData>()
                   .InnerJoin((t,d)=>d.dict_type==t.dict_type)
                   .Where((t,d)=> idList.Contains(t.id))
                   .ToList();

            if(dbres!=null&& dbres.Count >0)
                return SystemError<bool>(string.Format("字典{0}存在字典数据，请先删除字典数据",string.Join(",", dbres.Select(d => d.dict_type).Distinct())));


            saveRes = GCCEntrance.DBManager!.LocalDB!.Delete<SysDictType>().Where(x => idList.Contains(x.id)).ExecuteAffrows()>0;

            return HandleData(saveRes);
        }

        /// <summary>
        /// 查询字典子表列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getDataList")]
        public DataResponse<List<SysDictData>> GetDataList([FromQuery] SysParamDataRequest  request)
        {
            var dbres = GCCEntrance.DBManager!.LocalDB!.Select<SysDictData>()
                     .WhereIf(!string.IsNullOrWhiteSpace(request.dict_type), item => item.dict_type.Contains(request.dict_type!))
                     .WhereIf(!string.IsNullOrWhiteSpace(request.dict_label), item => item.dict_type.Contains(request.dict_label!))
                     .WhereIf(request.status.HasValue, item => item.status==request.status.Value!)
                     .Count(out var count)
                     .Page(request.PageIndex ?? 1, request.PageSize)
                     .OrderByDescending(x => x.dict_sort)
                     .ToList();

            return HandleData(dbres, count);
        }


        /// <summary>
        /// 查询字典子表详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("queryData/{id}")]
        public DataResponse<SysDictData> GetParamData([FromRoute] long id)
        {
            var res = GCCEntrance.DBManager!.LocalDB!.Queryable<SysDictData>().Where(x => x.id==id).First();

            return HandleData(res);
        }


        /// <summary>
        /// 添加字典子表
        /// </summary>
        /// <returns></returns>
        [HttpPost("addData")]
        public DataResponse<bool> AddParamData([FromBody] ParamDataDto request)
        {
            var saveRes = false;
            try
            {
                var isExists = GCCEntrance.DBManager.LocalDB.Select<SysDictData>().Where(a => a.dict_label == request.dict_label.Trim()).Any();
                if (isExists)
                    throw new Exception("字典标签已存在");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    request.Create(_context, HttpContext.GetToken()).Wait();
                    SysDictData sysDictData = BeanUtils.copy<SysDictData, ParamDataDto>(request);
                    sysDictData.dict_label=sysDictData.dict_label.Trim();
                    if (GCCEntrance.DBManager!.LocalDB!.Insert(sysDictData).ExecuteAffrows() != 1)
                    {
                        throw new Exception();
                    }

                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }

            return HandleData(saveRes);
        }



        /// <summary>
        /// 更新字典
        /// </summary>
        /// <returns></returns>
        [HttpPost("updateData")]
        public DataResponse<bool> UpdateParamData([FromBody] ParamDataDto request)
        {
            var saveRes = false;
            if (request.id<=0)
                return SystemError<bool>("id为空");
            try
            {

                var isExists = GCCEntrance.DBManager.LocalDB.Select<SysDictData>()
                    .Where(a => a.dict_label == request.dict_label.Trim()&&a.id!=request.id &&a.dict_type==request.dict_type).Any();
                if (isExists)
                    throw new Exception("字典标签已存在");

                GCCEntrance.DBManager!.LocalDB!.Transaction(() =>
                {
                    var sysDictData = GCCEntrance.DBManager.LocalDB.Select<SysDictData>().Where(a => a.id == request.id).First();
                    if (sysDictData!=null)
                    {
                        request.create_by = sysDictData.create_by;
                        request.create_date = sysDictData.create_date;
                        request.Modify(_context, HttpContext.GetToken()).Wait();

                        BeanUtils.copy<SysDictData, ParamDataDto>(request, ref sysDictData);
                        sysDictData.dict_label=sysDictData.dict_label.Trim();
                        if (GCCEntrance.DBManager.LocalDB.Update<SysDictData>(request.id).SetSource(sysDictData).ExecuteAffrows()<=0)
                        {
                            throw new Exception();
                        }
                    }              
                    saveRes=true;
                });
            }
            catch (Exception exe)
            {
                return SystemError<bool>(exe.Message);
            }
            return HandleData(saveRes);
        }


        /// <summary>
        /// 删除字典
        /// </summary>
        /// <returns></returns>
        [HttpDelete("deleteData/{ids}")]
        public DataResponse<bool> DeleteParamData([FromRoute] string ids)
        {
            var saveRes = false;
            if (string.IsNullOrWhiteSpace(ids))
                return SystemError<bool>("id为空");

            var idList = SysHelper.SpitIntArrary(ids);

            saveRes = GCCEntrance.DBManager!.LocalDB!.Delete<SysDictData>().Where(x => idList.Contains(x.id)).ExecuteAffrows()>0;

            return HandleData(saveRes);
        }


    }
}
